package com.xxx.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxx.common.Result;
import com.xxx.pojo.Explosive;
import com.xxx.service.ExplosiveService;
import com.xxx.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/explosive")
public class ExplosiveController {

    @Autowired
    private ExplosiveService explosiveService;

    @Autowired
    private FileService fileService;

    /**
     * 新增
     *
     * @param explosive
     * @return
     */
    @PreAuthorize("hasAnyAuthority('sys:add:explosive')")
    @Transactional
    @PostMapping("/save")
    public Result save(@RequestBody Explosive explosive) {
        log.info("explosive:{}", explosive);
        boolean save = explosiveService.save(explosive);
        return save ? Result.success("新增成功") : Result.error("保存失败");
    }

    @PreAuthorize("hasAuthority('sys:select:explosive')")
    @GetMapping("/get-explosive")
    public Result getInfo(Integer pageNo, Integer pageSize, String name) {
        IPage iPage = new Page(pageNo, pageSize);

        iPage = explosiveService.page(iPage, new LambdaQueryWrapper<Explosive>()
                .like(name != null && !"".equals(name), Explosive::getTitle, name)
                .orderByDesc(Explosive::getCreateTime));

        return Result.success("success", iPage);
    }


    @PreAuthorize("hasAnyAuthority('sys:delete:explosive')")
    @Transactional
    @DeleteMapping("/{id}")
    public Result delById(@PathVariable Long id) {
        Explosive explosive = explosiveService.getById(id);
        boolean b = explosiveService.removeById(id);
        fileService.delImage(explosive.getImg());

        return b ? Result.success("success") : Result.error("error");
    }

    @PreAuthorize("hasAuthority('sys:update:explosive')")
    @Transactional
    @PutMapping("/update")
    public Result update(@RequestBody Explosive explosive) {

        boolean b = explosiveService.updateById(explosive);
        return b ? Result.success("success") : Result.error("error");
    }

    @PostMapping("/get-data")
    public Result getExplosive() {
        List<Explosive> list = explosiveService.list(new LambdaQueryWrapper<Explosive>()
                .orderByDesc(Explosive::getId)
                .eq(Explosive::getStatus, 1)
                .last("limit 3"));
        return Result.success("success", list);
    }

}
